<?php


namespace app\admin\controller;

use app\admin\model\Community as CommunityModel;
use app\admin\model\SystemUploadfile;
use app\common\controller\AdminController;
use app\common\controller\Sms;
use app\common\job\SendSms;
use app\common\service\MenuService;
use EasyAdmin\upload\Uploadfile;
use think\db\Query;
use think\Exception;
use think\facade\Cache;
use app\admin\model\Community;
use app\admin\model\Form1;
use app\admin\model\Form2;
use app\admin\model\Form3;
use app\admin\model\Form4;
use app\admin\model\Form5;
use think\facade\Db;
use think\facade\Queue;

class Ajax extends AdminController
{

    /**
     * 初始化后台接口地址
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function initAdmin()
    {
        $cacheData = Cache::get('initAdmin_' . session('admin.id'));
        if (!empty($cacheData)) {
            return json($cacheData);
        }
        $menuService = new MenuService(session('admin.id'));
        $data = [
            'logoInfo' => [
                'title' => sysconfig('site', 'logo_title'),
                'image' => sysconfig('site', 'logo_image'),
                'href'  => __url('index/index'),
            ],
            'homeInfo' => $menuService->getHomeInfo(),
            'menuInfo' => $menuService->getMenuTree(),
        ];
        Cache::tag('initAdmin')->set('initAdmin_' . session('admin.id'), $data);
        return json($data);
    }

    /**
     * 清理缓存接口
     */
    public function clearCache()
    {
//        Cache::clear();
        $this->success('清理缓存成功');
    }

    /**
     * 上传文件
     */
    public function upload()
    {
        $data = [
            'upload_type' => $this->request->post('upload_type'),
            'file'        => $this->request->file('file'),
        ];
        $uploadConfig = sysconfig('upload');
        empty($data['upload_type']) && $data['upload_type'] = $uploadConfig['upload_type'];
        $rule = [
            'upload_type|指定上传类型有误' => "in:{$uploadConfig['upload_allow_type']}",
            'file|文件'              => "require|file|fileExt:{$uploadConfig['upload_allow_ext']}|fileSize:{$uploadConfig['upload_allow_size']}",
        ];
        $this->validate($data, $rule);
        try {
            $upload = Uploadfile::instance()
                ->setUploadType($data['upload_type'])
                ->setUploadConfig($uploadConfig)
                ->setFile($data['file'])
                ->save();
            if ($upload['save'] <> true) throw new Exception($upload['msg']);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success($upload['msg'], ['id' => $upload['id'], 'url' => $upload['url']]);
    }

    /**
     * 上传图片至编辑器
     * @return \think\response\Json
     */
    public function uploadEditor()
    {
        $data = [
            'upload_type' => $this->request->post('upload_type'),
            'file'        => $this->request->file('upload'),
        ];
        $uploadConfig = sysconfig('upload');
        empty($data['upload_type']) && $data['upload_type'] = $uploadConfig['upload_type'];
        $rule = [
            'upload_type|指定上传类型有误' => "in:{$uploadConfig['upload_allow_type']}",
            'file|文件'              => "require|file|fileExt:{$uploadConfig['upload_allow_ext']}|fileSize:{$uploadConfig['upload_allow_size']}",
        ];
        $this->validate($data, $rule);
        try {
            $upload = Uploadfile::instance()
                ->setUploadType($data['upload_type'])
                ->setUploadConfig($uploadConfig)
                ->setFile($data['file'])
                ->save();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        if ($upload['save'] == true) {
            return json([
                'error'    => [
                    'message' => '上传成功',
                    'number'  => 201,
                ],
                'fileName' => '',
                'uploaded' => 1,
                'url'      => $upload['url'],
            ]);
        } else {
            $this->error($upload['msg']);
        }
    }

    /**
     * 获取上传文件列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUploadFiles()
    {
        $get = $this->request->get();
        $page = isset($get['page']) && !empty($get['page']) ? $get['page'] : 1;
        $limit = isset($get['limit']) && !empty($get['limit']) ? $get['limit'] : 10;
        $title = isset($get['title']) && !empty($get['title']) ? $get['title'] : null;
        $this->model = new SystemUploadfile();
        $count = $this->model
            ->where(function (Query $query) use ($title) {
                !empty($title) && $query->where('original_name', 'like', "%{$title}%");
            })
            ->count();
        $list = $this->model
            ->where(function (Query $query) use ($title) {
                !empty($title) && $query->where('original_name', 'like', "%{$title}%");
            })
            ->page($page, $limit)
            ->order($this->sort)
            ->select();
        $data = [
            'code'  => 0,
            'msg'   => '',
            'count' => $count,
            'data'  => $list,
        ];
        return json($data);
    }

    public function getCommunityList()
    {
        $arr = ['id' => 0, 'name' => '无'];
        $list = Community::field('id,name')->select()->toArray();
        array_unshift($list, $arr);
        $this->success('获取成功', $list);
    }

    public function getForm4List()
    {
        $list = Form4::getList();
        $this->success('获取成功', $list);
    }

    // 定时触发异步任务
    // type 1体温上报14天  2疫苗异常上报2天  3购药人员上报14天  4集中隔离人员上报21天  5集中隔离人员第6天核酸检查
    public function task()
    {
        try {
            $result = [];

            $type = $this->request->param('type/d');
            if (empty($type)) throw new Exception('任务类型type不能为空');

            if ($type == 1) {
                // 返沙人员
                $result = Form1::where([
                    ['status', '=', 0],
                    ['count', '<', 28],
                ])
                ->order('id','desc')
                ->column('mobile', 'id');
            } else if ($type == 2) {
                // 疫苗接种人员
                $map1 = [
                    ['count', '=', 0],
                    ['status', '=', 0],
                ];
                $map2 = [
                    ['count', '>', 0],
                    ['status', '=', 0],
                    ['sms_time', '<>', ''],
                    ['sms_time', '<=', date('Y-m-d', time() - 7 * 24 * 60 * 60)],
                ];
                $result = Form2::whereOr([$map1, $map2])
                        ->order('id','desc')
                        ->column('mobile', 'id');
            } else if ($type == 3) {
                // 购药人员
//                $result = Form3::where([
//                    ['status', '=', 0],
//                    ['count', '<', 28],
//                ])
//                ->order('id','desc')
//                ->column('mobile', 'id');
            } else if ($type == 4) {
                // 集中隔离人员
                $result = Form5::where([
                    ['status', '=', 0],
                    ['count', '<', 42],
                    // 解除隔离时间到后才算
                    ['jc_time', '<=', date('Y-m-d H:i:s', time())]
                ])
                ->order('id','desc')
                ->column('mobile', 'id');
            } else if ($type == 5) {
                // 集中隔离人员第6天上门核酸
                $result = Form5::where([
                    ['status', '=', 0],
                    // 第6天
                    ['count', '=', 5],
                    // 解除隔离时间到后才算
                    ['jc_time', '<=', date('Y-m-d H:i:s', time())]
                ])
                ->order('id','desc')
                ->column('mobile', 'id');
            }

            //去重
            $result = array_unique($result,SORT_NUMERIC);

            if (!empty($result)) {
                // 分割成1000人一组
                $list = array_chunk($result, 1000, true);
                // 分批丢到异步任务系统
                foreach ($list as $v) {
                    $data = [
                        'type'  =>  $type,
                        'list'  =>  $v,
                    ];
                    Queue::push(SendSms::class, $data);
                }
            } else {
                throw new Exception('暂无满足条件的人员');
            }

        } catch (\Exception $e) {
            return $e->getMessage();
        }

        return 'success';
    }

    // 下载导入模板
    public function download_templet()
    {
        $name = $this->request->param('name/s');
        return download(public_path().'templet/'.$name, $name);
    }

    // 乡镇获取社区
    public function getCommunityList2()
    {
        $town = $this->request->param('town/d', 0);
        if ($town <> 1) {
            return result(1,'', [
                [
                    'value' =>  0,
                    'label' =>  '无',
                ],
            ]);
        }
        $list = CommunityModel::field('name as label,id as value')->select();
        return result(1,'',$list);
    }
}